# coding:utf-8

import cv2
from HumanDetect import FaceDetect, EyeDetect
import numpy
import sys

WINDOW_TITLE = 'Face Detect'

clicked = False


def on_mouse_callback(event, x, y, flags, param):
    global clicked
    if event == cv2.EVENT_LBUTTONUP:
        clicked = True


if __name__ == "__main__":
    camera_capture = cv2.VideoCapture(0)
    cv2.namedWindow(WINDOW_TITLE)
    cv2.setMouseCallback(WINDOW_TITLE, on_mouse_callback)
    face_detect = FaceDetect()
    eye_detect = EyeDetect()

    pic_pig = cv2.imread('pig.jpg')
    pig_height = len(pic_pig)
    pig_width = len(pic_pig[0])

    success, frame = camera_capture.read()

    window_height = len(frame)
    window_width = len(frame[0])

    while success and cv2.waitKey(1) == -1 and not clicked:
        img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        faces = face_detect.detect(img)
        eye = eye_detect.detect(img)

        for (x, y, w, h) in faces:
            replace_width = int(h * pig_width / pig_height)
            replace_height = h
            pig = cv2.resize(pic_pig, (replace_width, replace_height))
            #        frame = cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
            frame[y:y + replace_height, x:x + replace_width] = pig[:, :]

        for (x, y, w, h) in eye:
            replace_width = int(h * pig_width / pig_height)
            replace_height = h
            pig = cv2.resize(pic_pig, (replace_width, replace_height))
            #        frame = cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
            frame[y:y + replace_height, x:x + replace_width] = pig[:, :]

        cv2.imshow(WINDOW_TITLE, frame)
        success, frame = camera_capture.read()

    cv2.destroyAllWindows()
    camera_capture.release()
    sys.exit()
